package cn.com.chengmandian.company.filters;

import cn.com.chengmandian.core.common.constants.ResponseCode;
import cn.com.chengmandian.core.common.utils.UrlUtil;
import cn.com.chengmandian.core.redis.cache.AgentCacheService;
import cn.com.chengmandian.core.redis.cache.CompanyCacheService;
import cn.com.chengmandian.core.web.pojo.AgentInfo;
import cn.com.chengmandian.core.web.pojo.AjaxResult;
import cn.com.chengmandian.core.web.pojo.CompanyInfo;
import cn.com.chengmandian.core.web.utils.LocalMapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@Component
public class InnerAuthFilter extends OncePerRequestFilter {
    private final static String PARAM_COMPANY = "xCompanyId";

    @Autowired
    private CompanyCacheService companyCacheService;

    // 403 权限不足
    private void responseError(HttpServletResponse response, Integer code, String message) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSONUtil.toJsonStr(AjaxResult.error(code, message)));
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String requestURI = request.getRequestURI();

        if (!UrlUtil.filterUrls("/*/inner/**", requestURI)) {
            filterChain.doFilter(request, response);
            return;
        }
        String companyId = request.getParameter(PARAM_COMPANY);
        if (StrUtil.isBlank(companyId)) {
            responseError(response, ResponseCode.ACCESS_DENIED, "微服务接口，参数缺少企业标识");
            return;
        }
        CompanyInfo companyInfo = companyCacheService.getCompany(companyId);
        if (companyInfo == null) {
            responseError(response, ResponseCode.ACCESS_DENIED, "企业标识不存在");
            return;
        }
        LocalMapUtil.setCompanyInfo(companyInfo);
        filterChain.doFilter(request, response);
    }
}
